google.load('visualization', '1', {packages:['table']});

(function($) { 
	var window_count = 0;
	var services = {};

	$(document).ready(function(){
		// render links
		if(!window.spreadsheet_url){
			if( !Get_Cookie( 'flism_ignore_spreadsheet' ) ){
				flism_alert("FLISM Spreadsheet not found",'Please define the spreadsheet_url variable in order to use FLISM.<br/><ul><li><a href="#" class="ignore">Ignore</a></li><li><a href="http://code.google.com/p/flism/wiki/InstallFLISM">Read FLISM documentation</a></li></ul>',400);
			}
			return false;
		}
		$(".rdfas").each(function(){
			$(this).css({'cursor': 'pointer'});
			var field = $(this).attr("id");
			var value = $(this).text();
			$(this).mouseenter(function(){render_links_box($(this), field, value);});
			$(this).mouseleave(function(){if(!$("#rbox_"+field).find("ul:visible").length) $("#rbox_"+field).hide()});
		});
		$(".rdfas").click(function(){
			//lock box id clicked
			var value = $(this).text();
			var field = $(this).attr("id");
			var field_label = $(this).attr("rel");
			var content = $(this).find("span[content]").attr("content");
			get_links($(this), field, content, field_label);
		});
	});
	function render_link(link, label){
		window_count++;
		return $('<li><a href="'+link+'" target="_new'+window_count+'">'+label+'</a> <div class="class_block">&nbsp;</div></li>');
	}
	function get_links(source, field, content, field_label){
		services.content = content;
		services.field = field;
		$("#rbox_"+field).find(".flism_intro").hide();
		$("#rbox_"+field).prepend('<h1>Options for '+field_label+'</h1>');
		$("#rbox_"+field).prepend('<a href="#" class="close"><img src="/images/closebox.png" class="btn_close" title="Close Window" alt="Close" /></a>');
		if($("#rbox_"+field).find("ul:hidden").length){
			$("#rbox_"+field).find("ul").fadeIn();
			if($("#rbox_"+field+ "ul li").length)
				return false;
		}
		$(source).find("span").each(function(){
			var attrs = this.attributes;
			for (var idx in attrs) {
			        var attrName = attrs[idx].name;
				if (/^property$/.test(attrName)) {
					build_link(this, field);
				}
				if (/^typeof$/.test(attrName)) {
					log(attrName);
					build_link(this, field);
				}
				if (/^xml:lang$/.test(attrName)) {
					translate_link();
				}
			}
		});
	}
	function build_link(span){
		var key = $(span).attr("property");
		if(!key)
			key = $(span).attr("typeof");
		services.query = new google.visualization.Query(window.spreadsheet_url);
		services.query.setQuery("select * where B = '"+key+"'");
                services.query.send(handleQueryResponse);         
	}
	function handleQueryResponse(response) {
		if (response.isError()) {
			alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
			return;
		}
		var data = response.getDataTable();
		for( var i=0; i<data.getNumberOfRows(); i++){
			var url_template = data.getFormattedValue(i,4);
			var service_name = data.getFormattedValue(i,0);
			var type = data.getFormattedValue(i,5);
			var url = url_template.replace(/{CONTENT}/g,services.content);
			var li = render_link(url,'Look for "'+services.content +'" at '+service_name);
			$(li).find(".class_block").addClass(type);
			if($("#rbox_"+services.field+" ul").find("a[href="+$(li).find("a").attr("href")+"]").length<1)
				$("#rbox_"+services.field+" ul").append(li);
		}
	}
	/* Dissapointingly hardcoded template for tranlation (only from Latin to English!) */
	function translate_link(){
		window_count++;
		var li = $('<li><a href="http://www.archives.nd.edu/cgi-bin/words.exe?'+services.content+'" target="_new'+window_count+'">Look for a translation at Whittakers Words Latin Translator</a></li>');
		if($("#rbox_"+services.field+" ul").find("a[href="+$(li).find("a").attr("href")+"]").length<1)
			$("#rbox_"+services.field+" ul").append(li);
	}

	function render_links_box(source, field, value, field_label){
		var div = $("#rbox_"+field);
		if(!$("#rbox_"+field).length){
			div = $('<div class="flism_box" id="rbox_'+field+'"><span class="flism_intro">Click on "'+value+'" to see links...</span><ul></ul></div>');
		        $("body").append(div);
			$("#rbox_"+field+" ul").hide();
			var top = $(source).position().top;
			var left = $(source).position().left;
			var width = $(source).width();
			var height = $(source).height();

			if($.browser.msie && $.browser.version.substr(0,1)<7){ top=0;$(div).css({width: '300px'}); }

			$(div).css({"top": (top+(height*0)),"left": (left+(width*1))});
				
		}
		$(div).fadeIn();

	        $("#rbox_"+field+" .close").live("click", function(){
	                $("#rbox_"+field).hide();
			$("#rbox_"+field).find("ul").hide();
			$("#rbox_"+field).find("h1, a.close").remove("");
			$("#rbox_"+field).find(".flism_intro").show();
			return false;
	        });
		//uncomment for links box close on mouseleave...
/*	        $(div).mouseleave(function(){
	                $(this).hide();
			$("#rbox_"+field).find("ul").html("");
			$("#rbox_"+field).find("h1, h2").remove("");
			$("#rbox_"+field).find(".flism_intro").show();
	        });
*/
	}

	/********** Utilities *********/
	function getUrlVars()
	{
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++){
	        hash = hashes[i].split('=');
	        vars.push(hash[0]);
	        vars[hash[0]] = hash[1];
	    }
	    return vars;
	}
	function log(message){
		var annoyance = getUrlVars()['annoyance'];
      		if(window.console)
      			console.log(message);
		else if(annoyance == "body")
			$('body').prepend('<p style="color: #d00; font-weight: bold;">'+message+'</p>');
		else if(annoyance)
			alert(message);
	}
	function flism_alert(title,message,popWidth){
		$("body").append('<div id="flism_alert" class="flism_alert"><h2>'+title+'</h2><p>'+message+'</p></div>');

		//When you click on a link with class of poplight and the href starts with a # 
		if(!popWidth)
			popWidth = 300;
		$('#flism_alert').fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="/images/closebox.png" class="btn_close" title="Close Window" alt="Close" /></a>');
		//Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
		var popMargTop = ($('#flism_alert').height() + 80) / 2;
		var popMargLeft = ($('#flism_alert').width() + 80) / 2;
		//Apply Margin to Popup
		$('#flism_alert').css({
		    'margin-top' : -popMargTop,
		    'margin-left' : -popMargLeft
		});
		//Fade in Background
		$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
		$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
		//Close Popups and Fade Layer
		$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
		    $('#fade , .flism_alert').fadeOut(function() {
		        $('#fade, a.close').remove();  //fade them both out
		    });
		    return false;
		});	
		//Close Popups and Fade Layer and set cookie to stop showing message
		$('a.ignore').live('click', function() { //When clicking on the close or fade layer...
		    $('#fade , .flism_alert').fadeOut(function() {
		        $('#fade, a.close').remove();  //fade them both out
		    });
		    var d = new Date();
		    d.setUTCFullYear(d.getUTCFullYear()+1); //do not show this message to this browser for a year
		    Set_Cookie( 'flism_ignore_spreadsheet', 'true', d.toUTCString(), '/', '', '' );
		    return false;
		});	

	}
	function Set_Cookie( name, value, expires, path, domain, secure ){
		// set time, it is in milliseconds
/*		var today = new Date();
		today.setTime( today.getTime() );
*/	
		/*
		if the expires variable is set, make the correct
		expires time, the current script below will set
		it for x number of days, to make it for hours,
		delete * 24, for minutes, delete * 60 * 24
		*/
/*		if ( expires ){
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
*/	
		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}
	function Get_Cookie( check_name ) {
		// first we will split this cookie up into name/value pairs
		// note: document.cookie only returns name=value, not the other components
		var a_all_cookies = document.cookie.split( ';' );
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false; // set boolean t/f default f
	
		for ( i = 0; i < a_all_cookies.length; i++ )
		{
			// now we will split apart each name=value pair
			a_temp_cookie = a_all_cookies[i].split( '=' );
	
	
			// and trim left/right whitespace while we are at it
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
			// if the extracted name matches passed check_name
			if ( cookie_name == check_name )
			{
					b_cookie_found = true;
				// we need to handle case where cookie has no value but exists (no = sign, that is):
				if ( a_temp_cookie.length > 1 )
				{
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
				// note that in cases where cookie is initialized but no value, null is returned
				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if ( !b_cookie_found )
		{
			return null;
		}
	}

	function Delete_Cookie( name, path, domain ) {
		if ( Get_Cookie( name ) ) document.cookie = name + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}

})(jQuery);

